import React, { useRef, useEffect, useState } from "react";

const View = ({ src, alt }) => {
  const [imageSrc, setImageSrc] = useState("");
  const imgRef = useRef(null);
  console.log(src, alt);
  useEffect(() => {
    let observer;
    console.log(imgRef.current);
    if (imgRef.current) {
      observer = new IntersectionObserver(
        ([entry]) => {
          // 当图片进入可视区域时，设置图片地址进行加载
          console.log(entry.isIntersecting,entry,observer);
          if (entry.isIntersecting) {
            setImageSrc(src);
            observer.unobserve(imgRef.current);
          }
        },
        {
          rootMargin: "0px 0px 200px 0px", // 可视区域的边距设置为200px
        }
      );
      observer.observe(imgRef.current);
    }
    return () => {
      if (observer && observer.unobserve) {
        observer.unobserve(imgRef.current);
      }
    };
  }, [src]);

  return <img ref={imgRef} style={{ with: "400px", height: "400px", margin: "0" }} src={imageSrc} alt={alt} />;
};

export default View 
